package com.health.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.sun.deploy.net.URLEncoder;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

/**
 * @Description
 * @Author konglz
 * @Data 2023/3/29 16:54
 */
public class EasyExcelUtil<T> {

    /***
    * @Description: 导入excel文件
    * @return: java.util.List<T>
    * @Author: konglz
    * @Date: 2023/4/14
    */
    public List<T> readExcel(MultipartFile file, Class clazz) throws IOException {

        List<T> TList = new ArrayList<>();
        PageReadListener<T> TPageReadListener = new PageReadListener<T>(new Consumer<List<T>>() {
            @Override
            public void accept(List<T> list) {
                TList.addAll(list);
            }
        });
        TPageReadListener.BATCH_COUNT = 60;
        EasyExcel.read(file.getInputStream(), clazz, TPageReadListener).sheet().doRead();

        return TList;
    }

    /***
    * @Description: 将文件导出成excel
    * @return: void
    * @Author: konglz
    * @Date: 2023/4/14
    */
    public static <T>  void download(HttpServletResponse response, Class clazz, List<T> list) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), clazz).sheet("模板").doWrite(list);
    }


    /***
    * @Description: 将一个集合转成一个对象
    * @return: T
    * @Author: konglz
    * @Date: 2023/4/14
    */
    public static <T> T listToObject(Class<T> clazz, List list) throws InstantiationException, IllegalAccessException {
        List<Field> fields = Arrays.asList(clazz.getFields());
        if(fields.size() != list.size()) return null;
        T t = clazz.newInstance();
        for(int i = 0; i < fields.size(); i++){
            fields.get(i).setAccessible(true);
            fields.get(i).set(i, list.get(i));
        }
        return t;
    }

}
